package com.orange.core.config.alicloud.sms;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.orange.core.config.alicloud.AliCloudProperties;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(AsyncClient.class)
@ConditionalOnProperty(prefix = SmsProperties.PREFIX, name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(SmsProperties.class)
public class SmsAutoConfiguration {

    @ConditionalOnMissingBean
    @Bean
    public AsyncClient smsClient(AliCloudProperties aliCloudProperties, SmsProperties smsProperties) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliCloudProperties.getAccessKey())
                .accessKeySecret(aliCloudProperties.getSecretKey())
                .build());

        return AsyncClient.builder()
                .region(smsProperties.getRegion())
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(smsProperties.getEndpoint()))
                .build();
    }
}
